<?php
/**
 * Yjnic_Filter 签名方案
 *
 * 注意：无任何参数时，不作验签
 *
 * @package     Yjnic
 * @author      prettyyjnic <prettyyjnic@qq.com> 2015-12-27
 */

class Yjnic_Filter implements PhalApi_Filter {

    protected $_sign_name;
    protected $_configs;

    public function __construct($configs) {
        $this->_sign_name = $configs['sign_name'];
        $this->_configs = $configs;
    }

    //检查签名
    public function check() {
        $all_params = DI()->request->getAll();
        $service = $all_params['service'];
        unset($all_params['service']);
        if (DI()->debug) {//debug模式跳过
            return;
        }
        if (isset($all_params[$this->_sign_name])) {
            $sign = $all_params[$this->_sign_name];
            unset($all_params[$this->_sign_name]);
            $this->sign($service, $all_params, $this->_configs['sign_str']);
            if ($all_params[$this->_sign_name] == $sign) {
                return;
            }else{
                throw new PhalApi_Exception_BadRequest("SIGN IS NOT CORRECT", 401); 
            }
        }else{
            throw new PhalApi_Exception_BadRequest("SIGN CAN NOT BE EMPTY", 400); 
        } 
    }

    // 签名
    // $configs 和 service 要变
    public function sign($service, &$params, $sign_str){
        $params['sign_str'] = $sign_str;
        ksort($params);
        $sign = $params[$this->_sign_name] = md5($service . http_build_query( $params ));
        unset($params['sign_str']);
    }

}
